package com.mycompany.sportclubmanager;

import com.mycompany.helpclasses.PlayerDTO;
import com.mycompany.helpclasses.PlayerManager;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.util.List;
 
@UrlBinding("/players/{$event}/{player.id}")
public class PlayersActionBean implements ActionBean {
 
    final static Logger log = LoggerFactory.getLogger(PlayersActionBean.class);
 
    private ActionBeanContext context;

    protected PlayerManager playerManager = new PlayerManager();
    
    private PlayerDTO player;
    
    public PlayerDTO getPlayer(){
        return player;
    }
    
    public void setPlayer(PlayerDTO player){
        this.player = player;
    }
    
    public List<PlayerDTO> getPlayers(){
        return playerManager.findAll();
    }
 
    @DefaultHandler
    public Resolution all() {
        log.debug("all()");
        return new ForwardResolution("/players.jsp");
    }
    
    @Before(stages = LifecycleStage.BindingAndValidation, on = {"edit", "save", "delete"})
    public void loadPlayer() {
        String id = context.getRequest().getParameter("player.id");
        if (id == null) return;
        player = playerManager.find(Integer.parseInt(id));
    }
    
    public Resolution add() {
        log.debug("add() player={}", player);
        playerManager.create(player);
        return new RedirectResolution(this.getClass(), "all");
    }
    
    public Resolution edit() {
        log.debug("edit() player={}", player);
        return new ForwardResolution("/editplayer.jsp");
    }
    
    public Resolution save() {
        log.debug("save() player={}", player);
        playerManager.edit(player);
        return new RedirectResolution(this.getClass(), "all");
    }
    
    public Resolution delete() {
        log.debug("delete() player={}", player);
        playerManager.delete(player);
        return new RedirectResolution(this.getClass(), "all");
    }
    
    public Resolution cancel() {
        log.debug("cancel() player={}", player);
        return new RedirectResolution(this.getClass(), "all");
    }
 
    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }
 
    @Override
    public ActionBeanContext getContext() {
        return context;
    }
}